package cn.wolfcode.controller;

import cn.wolfcode.util.JsonResult;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/httpClients")
public class HttpClientController {

    @GetMapping("/reptilePoetry")
    public Object reptilePoetry(String url) throws IOException {
        //创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet实例
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String html = "";
        if (response != null){
            HttpEntity entity =  response.getEntity();  //获取网页内容
            String result = EntityUtils.toString(entity, "UTF-8");

            /*Document document = Jsoup.parse(result);
            Element content = document.getElementById("zs_content");
            html = content.html();*/

            if (result.contains("浔阳江头夜送客")) {
                int beg = result.indexOf("浔阳江头夜送客");
                int end = result.indexOf("江州司马青衫湿。")+8;
                html = result.substring(beg, end);
                System.out.println(html);
            }


            System.out.println();
        }
        if (response != null){
            response.close();
        }
        if (httpClient != null){
            httpClient.close();
        }
        return JsonResult.success(html);
    }
}
